##    This file is part of The Most Awesome Story Ever
##
##    Foobar is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    Foobar is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
##    
##    Copyright 2008, Ryan Michela

import wsgiref.handlers
import pagemodel
import pagerenderer
import pagemaker

from google.appengine.ext import webapp
from google.appengine.ext import db



class ImageHandler(webapp.RequestHandler):
  """This class loads an image from the database and writes its data to the
  output stream."""

  def get(self, pageNum, imageType):
    """Process the HTTP GET verb to load and write an image."""
    #load the image for the current page. if not found, return a 404
    page = self.queryPage(pageNum)
    if (page != None and isinstance(page.image, db.Blob)):
        self.response.headers['Content-Type'] = 'image/%s' % imageType
        self.response.out.write(page.image)
    else:
        self.error(404)
    
  def queryPage(self, pageNum):
    """Query the Pages database for a particular page. Return the page object
    if found or None if not."""
    try:
        #querry the db for the current page
        pages = db.GqlQuery("SELECT * FROM Page WHERE pageNum = :1", 
                                int(pageNum))
        return pages[0]
    except:
        return None
    

def main():
  """Handle all urls matching /images/page[#].[ext] where [#] is the first
  parameter and [ext] is the second parameter of the get() method."""
  application = webapp.WSGIApplication([('/images/page(.*)\.(.*)', ImageHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()